package com.desksoft.ecommerce.util.html.element.variable.calculate;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.GregorianCalendar;

/**
 * 日期类型运算Bean
 * $Calculate{date, year, 1, month, -2}
 * @param1 		运算Bean类型
 * @param2		需要追加在日期的哪部分，可选值:year | month | day 
 * @param3		需要追加多少
 * 例子中表示1年以后，当前月份的2月以前
 * @author Administrator
 *
 */
public class DateCalculateBean implements ICalculateBean {

	protected SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
	
	@Override
	public String getToken() {
		return "date";
	}

	@Override
	public String getVariable(String... params) {
		
		Calendar c = new GregorianCalendar();
		Integer increment = null;
		int part = -1;
		for (int i = 1 ; i < params.length ; i++){
			
			part = getPart(params[i]);
			
			if (++i >= params.length){
				break;
			}
			increment = getTime(params[i]);
			
			c.add(part, increment);
		}
		
		return sdf.format(c.getTime());
	}
	
	/**
	 * 获取日期增量
	 */
	public int getTime(String str){
		if (str == null){
			throw new RuntimeException("运算增量不能为空.");
		}
		
		Integer res = null;
		try{
			res = Integer.parseInt(str.trim());
		}catch(NumberFormatException ex){
			throw new NumberFormatException("不能将字符串[" + str + "]转换为数字.");
		}
		return res;
	}
	
	/**
	 * 获取运算日期区间
	 */
	public int getPart(String partString){
		
		DatePart part = null;
		try{
			part = DatePart.valueOf(partString.trim());
		}catch(IllegalArgumentException ex){
			throw new IllegalArgumentException("无法找到[" + partString + "]类型的日期区间", ex);
		}
		
		switch (part){
			case year: return Calendar.YEAR;
			case month: return Calendar.MONTH;
			case day: return Calendar.DATE;
			default: {
				return -1;
			}
		}
	}
}

/**
 * 运算部分
 * @author Administrator
 *
 */
enum DatePart {
	year,
	month,
	day
}
